<?php
// +----------------------------------------------------------------------
// | 授权系统 - 授权验证控制器（公开接口）
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace api\modules\admin\controllers\license;

use api\utils\libs\BaseController;
use common\services\system\LicenseService;
use Yii;

/**
 * 授权验证控制器（不需要登录）
 */
class ValidateController extends BaseController
{
    /**
     * 在线验证授权
     */
    public function actionCheck()
    {
        $licenseKey = $this->request->post('license_key');
        
        if (empty($licenseKey)) {
            return $this->error('授权码不能为空');
        }
        
        // 获取客户端信息
        $clientData = [
            'domain' => $this->request->post('domain'),
            'ip' => $this->request->post('ip') ?: Yii::$app->request->userIP,
            'machine_code' => $this->request->post('machine_code'),
            'user_agent' => Yii::$app->request->userAgent,
            'sdk_version' => $this->request->post('sdk_version'),
            'product_version' => $this->request->post('product_version'),
            'validate_type' => 'online',
        ];
        
        // 验证授权
        $result = LicenseService::validateLicense($licenseKey, $clientData);
        
        if ($result['success']) {
            return $this->success($result['message'], $result['data']);
        }
        
        return $this->error($result['message'], $result['error_code']);
    }
    
    /**
     * 获取授权信息（简化版，用于初始化）
     */
    public function actionInfo()
    {
        $licenseKey = $this->request->get('license_key');
        
        if (empty($licenseKey)) {
            return $this->error('授权码不能为空');
        }
        
        $license = \common\models\system\License::findOne(['license_key' => $licenseKey]);
        
        if (!$license) {
            return $this->error('授权码不存在');
        }
        
        return $this->success('', [
            'license_type' => $license->license_type,
            'license_level' => $license->license_level,
            'end_date' => $license->end_date,
            'status' => $license->status,
        ]);
    }
}

